package com.ruoyi.phoneController;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.domain.MobileUserCoupon;
import com.ruoyi.domain.MobileLoginUser;
import com.ruoyi.service.IMobileUserCouponService;
import com.ruoyi.service.MobileTokenService;

/**
 * 手机端用户优惠券Controller
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/mobile/userCoupon")
@CrossOrigin(origins = "*", maxAge = 3600)
public class MobileUserCouponController extends BaseController
{
    @Autowired
    private IMobileUserCouponService mobileUserCouponService;

    @Autowired
    private MobileTokenService mobileTokenService;

    /**
     * 查询用户优惠券列表
     */
    @GetMapping("/list")
    public AjaxResult list(MobileUserCoupon mobileUserCoupon)
    {
        try
        {
            List<MobileUserCoupon> list = mobileUserCouponService.selectMobileUserCouponList(mobileUserCoupon);
            return success(list);
        }
        catch (Exception e)
        {
            logger.error("查询用户优惠券列表失败", e);
            return error("查询失败");
        }
    }

    /**
     * 获取用户优惠券详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        if (id == null || id <= 0)
        {
            return error("优惠券ID不能为空");
        }

        try
        {
            MobileUserCoupon userCoupon = mobileUserCouponService.selectMobileUserCouponById(id);
            if (userCoupon == null)
            {
                return error("用户优惠券不存在");
            }
            return success(userCoupon);
        }
        catch (Exception e)
        {
            logger.error("获取用户优惠券详情失败", e);
            return error("获取用户优惠券详情失败");
        }
    }

    /**
     * 获取当前用户的优惠券列表（包含优惠券详细信息）
     */
    @GetMapping("/my/details")
    public AjaxResult getMyUserCouponsWithDetails()
    {
        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            Integer userId = loginUser.getUser().getId();
            List<MobileUserCoupon> list = mobileUserCouponService.selectUserCouponsWithDetails(userId);
            return success(list);
        }
        catch (Exception e)
        {
            logger.error("获取用户优惠券列表失败", e);
            return error("获取用户优惠券列表失败");
        }
    }

    /**
     * 获取当前用户的可用优惠券列表
     */
    @GetMapping("/my/available")
    public AjaxResult getMyAvailableUserCoupons()
    {
        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            Integer userId = loginUser.getUser().getId();
            List<MobileUserCoupon> list = mobileUserCouponService.selectAvailableUserCoupons(userId);
            return success(list);
        }
        catch (Exception e)
        {
            logger.error("获取用户可用优惠券列表失败", e);
            return error("获取用户可用优惠券列表失败");
        }
    }

    /**
     * 获取当前用户在指定商家的可用优惠券列表（用于订单页面选择优惠券）
     */
    @GetMapping("/my/available/{merchantId}")
    public AjaxResult getMyAvailableUserCouponsByMerchant(@PathVariable("merchantId") Integer merchantId)
    {
        if (merchantId == null || merchantId <= 0)
        {
            return error("商家ID不能为空");
        }

        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            Integer userId = loginUser.getUser().getId();
            List<MobileUserCoupon> list = mobileUserCouponService.selectAvailableUserCouponsByMerchant(userId, merchantId);
            return success(list);
        }
        catch (Exception e)
        {
            logger.error("获取用户在指定商家的可用优惠券列表失败", e);
            return error("获取优惠券列表失败");
        }
    }

    /**
     * 领取优惠券
     */
    @PostMapping("/receive")
    public AjaxResult receiveCoupon(@RequestBody ReceiveCouponRequest request)
    {
        if (request == null || request.getCouponId() == null || request.getCouponId() <= 0)
        {
            return error("优惠券ID不能为空");
        }

        try
        {
            MobileLoginUser loginUser = mobileTokenService.getLoginUser();
            if (loginUser == null || loginUser.getUser() == null)
            {
                return error("用户未登录或登录已过期");
            }

            Integer userId = loginUser.getUser().getId();
            int result = mobileUserCouponService.receiveCoupon(userId, request.getCouponId());
            
            if (result > 0)
            {
                return success("优惠券领取成功");
            }
            else
            {
                return error("优惠券领取失败");
            }
        }
        catch (RuntimeException e)
        {
            logger.error("领取优惠券失败: {}", e.getMessage());
            return error(e.getMessage());
        }
        catch (Exception e)
        {
            logger.error("领取优惠券失败", e);
            return error("领取优惠券失败");
        }
    }

    /**
     * 使用优惠券
     */
    @PostMapping("/use")
    public AjaxResult useCoupon(@RequestBody UseCouponRequest request)
    {
        if (request == null || request.getUserCouponId() == null || request.getUserCouponId() <= 0)
        {
            return error("用户优惠券ID不能为空");
        }

        if (request.getOrderId() == null || request.getOrderId() <= 0)
        {
            return error("订单ID不能为空");
        }

        try
        {
            int result = mobileUserCouponService.useCoupon(request.getUserCouponId(), request.getOrderId());
            
            if (result > 0)
            {
                return success("优惠券使用成功");
            }
            else
            {
                return error("优惠券使用失败");
            }
        }
        catch (RuntimeException e)
        {
            logger.error("使用优惠券失败: {}", e.getMessage());
            return error(e.getMessage());
        }
        catch (Exception e)
        {
            logger.error("使用优惠券失败", e);
            return error("使用优惠券失败");
        }
    }

    /**
     * 新增用户优惠券
     */
    @PostMapping
    public AjaxResult add(@RequestBody MobileUserCoupon mobileUserCoupon)
    {
        try
        {
            return toAjax(mobileUserCouponService.insertMobileUserCoupon(mobileUserCoupon));
        }
        catch (Exception e)
        {
            logger.error("新增用户优惠券失败", e);
            return error("新增失败");
        }
    }

    /**
     * 修改用户优惠券
     */
    @PutMapping
    public AjaxResult edit(@RequestBody MobileUserCoupon mobileUserCoupon)
    {
        try
        {
            return toAjax(mobileUserCouponService.updateMobileUserCoupon(mobileUserCoupon));
        }
        catch (Exception e)
        {
            logger.error("修改用户优惠券失败", e);
            return error("修改失败");
        }
    }

    /**
     * 删除用户优惠券
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Integer id)
    {
        try
        {
            return toAjax(mobileUserCouponService.deleteMobileUserCouponById(id));
        }
        catch (Exception e)
        {
            logger.error("删除用户优惠券失败", e);
            return error("删除失败");
        }
    }

    /**
     * 领取优惠券请求对象
     */
    public static class ReceiveCouponRequest
    {
        private Integer couponId;

        public Integer getCouponId()
        {
            return couponId;
        }

        public void setCouponId(Integer couponId)
        {
            this.couponId = couponId;
        }
    }

    /**
     * 使用优惠券请求对象
     */
    public static class UseCouponRequest
    {
        private Integer userCouponId;
        private Long orderId;

        public Integer getUserCouponId()
        {
            return userCouponId;
        }

        public void setUserCouponId(Integer userCouponId)
        {
            this.userCouponId = userCouponId;
        }

        public Long getOrderId()
        {
            return orderId;
        }

        public void setOrderId(Long orderId)
        {
            this.orderId = orderId;
        }
    }
}
